package com.reesechou.system;

import com.reesechou.javabean.SiteConfig;
import com.reesechou.javabean.User;
import com.reesechou.service.SiteConfigService;
import com.reesechou.service.UserService;
import org.directwebremoting.util.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.http.HttpServlet;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 小星打屁屁 on 2015/3/11.
 * com.reesechou.system
 */
public class SystemInitServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final Logger logger = Logger.getLogger(SystemInitServlet.class);
    @Override
    public void init(){
        Properties pro = new Properties();
        InputStream is = null ; //一个输入read流
        is = this.getClass().getResourceAsStream("/resources/dibmvc.properties");
        try{
            pro.load(is);
            Set keySet = pro.keySet();
            for(Iterator it = keySet.iterator();it.hasNext();){//获取set的迭代器，并判断是否有下一个
               String key = (String)it.next();
               String value = pro.getProperty(key);
               System.out.print("value: "+value);
               SystemConfig.getSystemConfig().put(key,value);
            }
            try{
                initDataBase();
//                initPageTemplate(); 初始化模板
            }catch (ParseException e){
                logger.error("初始数据库的日期转换出错了 "+e.getStackTrace());
            }
            logger.info("================================系统配置成功！！！！========================");
        }catch (Exception e){
            logger.error("系统初始化出错 "+e.getStackTrace());
            e.printStackTrace();
        }
    }

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SystemInitServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public  void initDataBase() throws ParseException{
        //这里数据库首先尝试的是直接使用 new 来获取相对应的对象，看看会有什么情况发生
//        UserService userService = new UserServiceImp();
        ApplicationContext beanFactory  = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        UserService userService = (UserService)beanFactory.getBean("userService");
        List<User> userList = userService.findAllUser();
        /**
         * 系统初始化还没有任何的数据时， 默认添加一个管理员用户
         */
        if(userList.size()<1&&userList!=null){
            User user = new User();
            user.setUsername(SystemConfig.getSystemConfig().get("ExtendLoveJ.user.username"));
            user.setPassword(SystemConfig.getSystemConfig().get("ExtendLoveJ.user.password"));
            user.setNickname(SystemConfig.getSystemConfig().get("ExtendLoveJ.user.nickname"));

            user.setAge(Integer.parseInt(SystemConfig.getSystemConfig().get("ExtendLoveJ.user.age")));
            user.setQq(SystemConfig.getSystemConfig().get("ExtendLoveJ.user.qq"));
            user.setEmail(SystemConfig.getSystemConfig().get("ExtendLoveJ.user.email"));
            user.setDescription(SystemConfig.getSystemConfig().get("ExtendLoveJ.user.description"));
            user.setGender(Boolean.parseBoolean(SystemConfig.getSystemConfig().get("ExtendLoveJ.user.gender")));
            user.setRoleType(Integer.parseInt(SystemConfig.getSystemConfig().get("ExtendLoveJ.user.roleType")));

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            user.setBirthday(format.parse(SystemConfig.getSystemConfig().get("ExtendLoveJ.user.birthday")));
            Date createTime = new Date();
            user.setCreateTime(createTime);

            userService.insert(user);
        }
        /**
         * 从配置文件中获取 siteConfig 的配置内容
         */
//        SiteConfigService siteConfigService = new SiteConfigServiceImp();
        SiteConfigService siteConfigService = (SiteConfigService)beanFactory.getBean("siteConfigService");
        SiteConfig siteConfig = new SiteConfig();

        siteConfig = siteConfigService.findAllSiteConfig();
        //如果数据库中没有任何的信息才出读取配置文件的相关信息并且保存到数据库中去
        if(siteConfig == null ){
            SiteConfig entity = new SiteConfig();
            entity.setAbout(SystemConfig.getSystemConfig().get("ExtendLoveJ.siteConfig.about"));
            entity.setContactDescription(SystemConfig.getSystemConfig().get("ExtendLoveJ.siteConfig.contactDescription"));
            entity.setIcp(SystemConfig.getSystemConfig().get("ExtendLoveJ.siteConfig.icp"));
            entity.setName(SystemConfig.getSystemConfig().get("ExtendLoveJ.siteConfig.name"));
            entity.setUrl(SystemConfig.getSystemConfig().get("ExtendLoveJ.siteConfig.url"));

            siteConfigService.insert(entity);
        }

    }
}
